import * as PIXI from 'pixi.js'
import Mini3d from './mini3d'
import { Math2 } from './utils/math'

// 天空
export default class Sky {
  constructor() {
    this.view = new PIXI.Container()
    this.clouds = []
    this.range = 3e3
    this.speed = -15
    this.count = 0
    this.createSky()
  }

  createSky() {
    let textureCache = PIXI.utils.TextureCache

    // 天空背景
    const skyBG = PIXI.Sprite.from(textureCache.skyBG)
    skyBG.width = window.innerWidth
    skyBG.height = window.innerHeight
    skyBG.anchor.set(0.5)
    skyBG.x = window.innerWidth / 2
    skyBG.y = window.innerHeight / 2
    this.view.addChild(skyBG)

    // 云
    this.mini3d = new Mini3d()
    this.createClouds([textureCache.skyCloud1, textureCache.skyCloud2])
    this.view.addChild(this.mini3d.view)
  }

  createClouds(cloudsTC) {
    // 云对象
    const cloudObject = (texture) => {
      const cloud = PIXI.Sprite.from(texture)
      cloud.anchor.set(0.5)
      cloud.position3d = { x: 0, y: 0, z: 0 }
      cloud.scaleRatio = 2
      cloud.scaleOffset = new PIXI.Point(1, 1)
      return cloud
    }

    // 创建云
    for (let i = 0; 50 > i; i++) {
      const cloud = cloudObject(cloudsTC[i % 2])
      cloud.position3d.z = -(this.range / 50) * i
      this.mini3d.addChild(cloud)
      this.clouds.push(cloud)
    }
  }

  update() {
    // 每一个云的运动 更新的
    for (let i = 0, len = this.clouds.length; i < len; i++) {
      let cloud = this.clouds[i]
      cloud.position3d.z += this.speed
      cloud.position3d.z < 300 ? (cloud.alpha = cloud.position3d.z / 300) : (cloud.alpha += 0.01 * (1 - cloud.alpha))
      if (cloud.position3d.z < 0) {
        cloud.scaleRatio = 5
        cloud.position3d.z += this.range
        cloud.position3d.x = Math2.random(-4500, 4500)
        cloud.position3d.y = 1200 - Math.abs(0.2 * cloud.position3d.x) + Math2.random(0, 200)
        cloud.rotation = cloud.position3d.x * -2e-4
        cloud.alpha = 0
        cloud.scaleOffset.x = Math2.random(0.6, 1.4)
        cloud.scaleOffset.y = Math2.random(0.9, 1.1)
        Math.random() < 0.5 && (cloud.scaleOffset.x *= -1)
      }
    }

    this.mini3d.update()
    this.count++
    this.mini3d.rotation = 0.08 * Math.cos(0.02 * this.count)
    this.mini3d.position3d.y = 200 * Math.sin(0.03 * this.count)
    this.mini3d.position3d.y -= 50
    this.mini3d.rotation3d.y = 0.2 * Math.sin(0.02 * this.count * 0.5)
  }
}
